package cn.tedu._05mvcboot03.base.exception;

import cn.tedu._05mvcboot03.base.response.JsonResult;
import cn.tedu._05mvcboot03.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        String data = ex.getMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        /*获取dto类属性值校验时异常提示消息*/
        String data = ex.getFieldError().getDefaultMessage();
        log.error(data);
        return  new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex){
        String data = ex.getMessage();
        return  new JsonResult(StatusCode.OPERATION_FAILED,data);
    }
}
